package com.sz.app.oss.api.logistics.price;

import com.sz.biz.app.web.BaseController;
import com.sz.biz.logistics.base.service.RegionSchemaService;
import com.sz.biz.logistics.base.service.WeightSchemaService;
import com.sz.biz.logistics.base.dto.RegionSchemaDto;
import com.sz.biz.logistics.base.dto.WeightSchemaDto;
import com.sz.biz.logistics.constants.ListStatusQueryConstants;
import com.sz.biz.logistics.core.dto.QuotationRegionDto;
import com.sz.biz.logistics.core.service.QuotationService;
import com.sz.biz.logistics.core.dto.QuotationDto;
import com.sz.biz.logistics.core.dto.QuotationGradeDto;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.customer.dto.CusCustomerDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.exception.BizException;
import com.sz.common.base.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Function: 报价方案. <br>
 * Date: 2017年03月20日 14:35 <br>
 * Author: wentao.chang
 */
@RestController
@RequestMapping("/api/v1/biz/quotations")
@Api(description = " ", tags = "035-000、价格-报价方案管理-无权限基础部分")
public class QuotationController extends BaseController {

    public static final String UNDEFINED = "undefined";
    private static String NULLUID = "-1";
    @Autowired
    private QuotationService quotationService;

    @Autowired
    private WeightSchemaService weightSchemaService;

    @Autowired
    private RegionSchemaService regionSchemaService;


    @Autowired
    private CustomerService customerService;

    /**
     * 根据报价方案的分区和重量段获取两个行列表头数据
     */
    @ApiOperation(value = "按选定的分区重量段获取报价方案表格的列头和行头", notes = "按选定的分区重量段获取报价方案表格的列头和行头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "regionSchemaUid", value = "分区方案uid", dataType = "string",
                    paramType = "path", required = true),
            @ApiImplicitParam(name = "weightSchemaUid", value = "重量段方案uid", dataType = "string",
                    paramType = "path", required = true)
    })
    @RequestMapping(value = "/{regionSchemaUid}/{weightSchemaUid}/sheetheaders", method = {RequestMethod.GET})
    public ResultDto queryRegionAndWeightDetail(@PathVariable String regionSchemaUid,
                                                @PathVariable String weightSchemaUid) {
        Map<String, Object> map = new HashMap<>(16);
        if(!NULLUID.equals(weightSchemaUid)){
            WeightSchemaDto wdto = weightSchemaService.findActivedByUid(weightSchemaUid);
            map.put("weights", wdto);
            map.put("weightUnit", wdto.getUnit());
        }else{
            map.put("weights", null);
            map.put("weightUnit", "kg");
        }
        if(!NULLUID.equals(regionSchemaUid)&&!UNDEFINED.equals(regionSchemaUid)){
            RegionSchemaDto rDto = regionSchemaService.findActivedByUid(regionSchemaUid);
            map.put("regions", rDto);
        }else{
            map.put("regions", null);
        }


        ResultDto result = new ResultDto();
        result.setData(map);
        return result;
    }

    @ApiOperation(value = "获取价格列表", notes = "获取价格列表，返回价格列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "1成本(默认) 2销售", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "biz", value = "服务或者产品的uid", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "q", value = "查询的关键字", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "gradeType", value = "-1全部(默认)1等级价 2协议价", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "grades", value = "1~5级", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "currencyId", value = "货币code", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "feeTypeCode", value = "费用类型code 全部为0(默认)", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "feeTypeId", value = "费用类型id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "settleMentId", value = "结算方式id", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "starts", value = "起运地", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "cargoTypeCode", value = "货物类型", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "startEffectTime", value = "生效时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "endEffectTime", value = "失效时间", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态：-1全部(默认) -2(审核列表的默认值) 1草稿 2提交审核 3已审核 4已启用 5已停用",
                    dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "includeAllAudit", value = "仅当status为3时，是否包含审核以上的状态",
                    dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orderby", value = "排序字段:草稿列表code(默认) 待审核列表submittime",
                    dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageIndex", value = "分页 默认第一页", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "asc", value = "排序方式", dataType = "boolean", paramType = "query", defaultValue = "true")})
    @RequestMapping(value = "/search", method = {RequestMethod.GET})
    public ResultDto getQuotations(@RequestParam(required = false, defaultValue = "1") String type,
                                   @RequestParam(required = false, defaultValue = "") String biz,
                                   @RequestParam(required = false, defaultValue = "") String q,
                                   @RequestParam(required = false, defaultValue = "-1") int gradeType,
                                   @RequestParam(required = false, defaultValue = "-1") String grades,
                                   @RequestParam(required = false, defaultValue = "0") String currencyId,
                                   @RequestParam(required = false, defaultValue = "0") String feeTypeCode,
                                   @RequestParam(required = false, defaultValue = "0") int feeTypeId,
                                   @RequestParam(required = false, defaultValue = "0") int settleMentId,
                                   @RequestParam(required = false, defaultValue = "") String starts,
                                   @RequestParam(required = false, defaultValue = "") String cargoTypeCode,
                                   @RequestParam(required = false, defaultValue = "") String startEffectTime,
                                   @RequestParam(required = false, defaultValue = "") String endEffectTime,
                                   @RequestParam(required = false, defaultValue = "-1") int status,
                                   @RequestParam(required = false, defaultValue = "false") boolean includeAllAudit,
                                   @RequestParam(required = false, defaultValue = "code") String orderby,
                                   @RequestParam(required = false, defaultValue = "1") int pageIndex,
                                   @RequestParam(required = false, defaultValue = "10") int pageSize,
                                   @RequestParam(required = false, defaultValue = "true") Boolean asc)

            throws BizException {
        q = StringUtils.replaceSqlPattern(q);
        QueryParams params = new QueryParams(pageSize, pageIndex, q, null,asc);
        grades = grades.trim();
        String[] gradeArr = grades.split(",");
        params.put("type", type);
        params.put("grades", gradeArr);
        params.put("gradeType", gradeType);
        params.put("currencyCode", currencyId);
        params.put("feeTypeCode", feeTypeCode);
        params.put("feeTypeId", feeTypeId);
        params.put("settlementId", settleMentId);
        starts = StringUtils.replaceSqlPattern(starts);
        params.put("starts", starts);
        params.put("cargoTypeCode", cargoTypeCode);
        params.put("startEffectTime", startEffectTime);
        params.put("endEffectTime", endEffectTime);
        params.put("asc", asc);
        params.put("biz", biz);
        int realIsOnline = -1;
        int realStatus = -1;
        if (status == ListStatusQueryConstants.Status.ALL) {
            realIsOnline = -1;
            realStatus = -1;
        }
        if (status == ListStatusQueryConstants.Status.AUDIT_ALL) {
            realIsOnline = -1;
            realStatus = 3;
        }
        if (status == ListStatusQueryConstants.Status.DRAFTS ||
                status == ListStatusQueryConstants.Status.PENDING_AUDIT ||
                status == ListStatusQueryConstants.Status.AUDIT_PASS) {
            realIsOnline = -2;
            realStatus = status;
        }
        if (status == ListStatusQueryConstants.Status.ENABLED) {
            realStatus = 3;
            realIsOnline = 1;
        }
        if (status == ListStatusQueryConstants.Status.DISABLE) {
            realStatus = 3;
            realIsOnline = 0;
        }
        if (status == ListStatusQueryConstants.Status.AUDIT_PASS && includeAllAudit) {
            realIsOnline = -1;
        }
        params.put("isOnline", realIsOnline);
        params.put("status", realStatus);
        params.put("orderby", orderby);
        ResultDto rdto = quotationService.findByFilter(params);

        List<QuotationDto> sDtos = (List<QuotationDto>) rdto.getData();
        if ("2".equals(type)) {
            for (QuotationDto dto : sDtos) {
                if (dto.getGradeType() == 1) {
                    if (dto.getGrade() == 1) {
                        dto.setGradeOrCustomerName("一级");
                    }
                    if (dto.getGrade() == 2) {
                        dto.setGradeOrCustomerName("二级");
                    }
                    if (dto.getGrade() == 3) {
                        dto.setGradeOrCustomerName("三级");
                    }
                    if (dto.getGrade() == 4) {
                        dto.setGradeOrCustomerName("四级");
                    }
                    if (dto.getGrade() == 5) {
                        dto.setGradeOrCustomerName("五级");
                    }
                }
                if (dto.getGradeType() == 2) {
                    CusCustomerDto cusCustomerDto = customerService.findById(dto.getCustomerId());
                    if (cusCustomerDto != null) {
                        dto.setGradeOrCustomerName(cusCustomerDto.getUserName());
                    }
                }
            }
        }
        return rdto;
    }

    @ApiOperation(value = "根据产品的UID查询价格等级的列表", notes = "根据产品的UID查询价格等级的列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productUid", value = "产品的uid", dataType = "string", paramType = "path")
    })
    @RequestMapping(value = "/{productUid}/grades", method = {RequestMethod.GET})
    public ResultDto findQuotationGrades(@PathVariable String productUid) {
        ResultDto dto = new ResultDto();
        List<QuotationGradeDto> dtos = quotationService.findQuotationGrades(productUid);
        dto.setData(dtos);
        return dto;
    }

    @ApiOperation(value = "根据服务查询一个参考的成本价格分区", notes = "根据服务查询一个参考的成本价格分区")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "quotationUid", value = "报价的uid", dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "serviceUid", value = "服务的uid", dataType = "string", paramType = "path"),
    })
    @RequestMapping(value = "/cost/{quotationUid}/{serviceUid}/region", method = {RequestMethod.GET})
    public ResultDto findCostQuotationRegion(@PathVariable String quotationUid, @PathVariable String serviceUid) {
        ResultDto dto = new ResultDto();
        QuotationRegionDto result = quotationService.findQuotationRegion(quotationUid, serviceUid);
        dto.setData(result);
        return dto;
    }
}

